package drds.server.sqlparser.sqlobject.statement.update;

import java.util.ArrayList;
import java.util.List;

import drds.server.sqlparser.sqlobject.expression.Expression;
import drds.server.sqlparser.sqlobject.expression.name.IName;
import drds.server.sqlparser.sqlobject.statement.StatementImpl;
import drds.server.sqlparser.visitor.Visitor;

/**
 * 
 * @author 曹正辉<330937205@qq.com>
 * 
 */
public class UpdateStatement extends StatementImpl {
	protected IName tableName;
	protected final List<UpdateSetItem> updateItemList = new ArrayList<UpdateSetItem>();
	protected Expression where;

	public UpdateStatement() {

	}

	public void setTableName(IName tableName) {
		this.tableName = tableName;
	}

	public IName getTableName() {
		return tableName;
	}

	public void addUpdateSetItem(UpdateSetItem updateItem) {
		this.updateItemList.add(updateItem);
		updateItem.setParent(this);
	}

	public List<UpdateSetItem> getUpdateItemList() {
		return updateItemList;
	}

	public void setWhere(Expression where) {
		if (where != null) {
			where.setParent(this);
		}
		this.where = where;
	}

	public Expression getWhere() {
		return where;
	}

	@Override
	public void output(StringBuffer sb) {
		sb.append("update ");

		this.tableName.output(sb);

		sb.append(" set ");
		for (int i = 0, size = updateItemList.size(); i < size; ++i) {//
			if (i != 0) {
				sb.append(", ");
			}
			updateItemList.get(i).output(sb);
		}

		if (this.where != null) {
			sb.append(" where ");
			this.where.output(sb);
		}
	}

	@Override
	protected void accept0(Visitor visitor) {
		if (visitor.visit(this)) {
			acceptChild(visitor, tableName);
			acceptChild(visitor, updateItemList);
			acceptChild(visitor, where);
		}
		visitor.endVisit(this);
	}
}
